package com.colin.util.util;


import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * elasticsearch 导入文件生成
 */
public class EsImport {
    /**
     * 源文件路径
     */
    private static final String ORING_FILE = "/static/json.txt";
    /**
     * 生成文件路径
     */
    private static final String TARGET_FILE = "C:\\Users\\zhaolz\\Desktop\\json.json";
    private static final String ENCODING = "UTF-8";
    private static Map<String, Map<String, String>> INDEX_INFO = null;

    static{
        //初始化es索引信息
        INDEX_INFO = new HashMap<>();
        Map<String, String> indexs = new HashMap<>();
        indexs.put("_index", "test");
        indexs.put("_type", "test");
        INDEX_INFO.put("index", indexs);
    }

    private static void generateJsonFile(){
        InputStreamReader read = null;
        BufferedReader bufferedReader = null;
        try{
            //创建输出文件
            File file = new File(TARGET_FILE);
            if (!file.exists()) {
                file.createNewFile();
            }

            read = new InputStreamReader(EsImport.class.getResourceAsStream(ORING_FILE),ENCODING);
            bufferedReader = new BufferedReader(read);
            for(String txt = null;(txt = bufferedReader.readLine()) != null;){
                Map<String, String> content = new HashMap<>();
                content.put("content", txt);
                FileWriter filew = new FileWriter(TARGET_FILE,true);
                //true表示追加，否则是覆盖写，覆盖写不需要true
                filew.write(JSONObject.toJSONString(INDEX_INFO) + "\n" +
                        JSONObject.toJSONString(content) + "\n");
                filew.flush();
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if(null != bufferedReader){
                    bufferedReader.close();
                }
                if(read != null){
                    read.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        System.out.println("开始生成。。。");
        long beginTime = System.currentTimeMillis();
        generateJsonFile();
        long endTime = System.currentTimeMillis();
        System.out.println("总共消耗时间为：" + (endTime - beginTime));
    }
}
